import React from "react";
import { Card, Button, Space, Tag, Typography, Input, Form } from "antd";
import { useRequest } from "ahooks";
import { history } from "umi";

const { Text, Paragraph } = Typography;

// 模拟 API 请求
const fetchUserInfo = (
  id: number
): Promise<{ id: number; name: string; email: string }> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        id,
        name: `用户${id}`,
        email: `user${id}@example.com`,
      });
    }, 1000);
  });
};

const ManualPage: React.FC = () => {
  const [form] = Form.useForm();

  const { data, loading, error, run } = useRequest(fetchUserInfo, {
    manual: true, // 手动触发，不会自动执行
  });

  const handleSubmit = (values: { userId: number }) => {
    run(values.userId);
  };

  return (
    <div style={{ padding: "24px" }}>
      <Button
        onClick={() => history.push("/")}
        style={{ marginBottom: "16px" }}
      >
        返回首页
      </Button>

      <Card
        title="useRequest 手动触发 (manual)"
        style={{ marginBottom: "16px" }}
      >
        <Paragraph>
          <Text strong>功能说明：</Text> 测试 manual 参数，设置为 true
          时不会自动执行请求，需要手动调用 run 方法。
        </Paragraph>

        <Space direction="vertical" style={{ width: "100%" }}>
          <div>
            <Text strong>状态：</Text>
            {loading && <Tag color="processing">加载中...</Tag>}
            {error && <Tag color="error">错误: {error.message}</Tag>}
            {data && <Tag color="success">成功</Tag>}
            {!data && !loading && !error && <Tag color="default">未请求</Tag>}
          </div>

          <Form form={form} onFinish={handleSubmit} layout="inline">
            <Form.Item
              name="userId"
              label="用户ID"
              rules={[{ required: true, message: "请输入用户ID" }]}
            >
              <Input
                type="number"
                placeholder="请输入用户ID"
                style={{ width: 120 }}
              />
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit" loading={loading}>
                获取用户信息
              </Button>
            </Form.Item>
          </Form>

          {data && (
            <div>
              <Text strong>数据：</Text>
              <div style={{ marginTop: "8px" }}>
                <p>ID: {data.id}</p>
                <p>姓名: {data.name}</p>
                <p>邮箱: {data.email}</p>
              </div>
            </div>
          )}
        </Space>
      </Card>
    </div>
  );
};

export default ManualPage;
